package my.sa;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;

public class ClassDetail {
	
	private String filePath;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String testPath = "E:/parttimework/毕业设计项目/Java静态分析/Test.class";
		ClassDetail cd = new ClassDetail(testPath);
		String r = cd.getClassDetail();
		System.out.println(r);
	}

	public ClassDetail(String filePath){
		this.filePath = filePath;
	}
	
	@SuppressWarnings("unchecked")
	public String getClassDetail(){
		StringBuilder sb = new StringBuilder();
		try {
			ClassReader classReader = new ClassReader(new FileInputStream(filePath));
			ClassNode node = new ClassNode();
			classReader.accept(node, 0);
			
			sb.append("类名：").append(node.name).append("\r\n");
			sb.append("超类：").append(node.superName.replace("/", ".")).append("\r\n");
			
			List<String> interfaces = node.interfaces;
			sb.append("\r\n实现接口列表：\r\n");
			if(interfaces==null || interfaces.size()==0){
				sb.append("----没有实现接口\r\n");
			}else{
				int i=0;
				for(String itf:interfaces){
					sb.append("接口：").append(i++).append(":").append(itf);
				}
			}
			sb.append("\r\n<=========================>");
			
			sb.append("成员属性列表：\r\n");
			List<FieldNode> fields = node.fields;
			if(null == fields || fields.size()==0){
				sb.append("----没有成员属性\r\n");
			}else{
				for(FieldNode fn:fields){
					sb.append("属性名：").append(fn.name).append("\t签名:").append(fn.signature).append("\t值:").append(fn.value);
				}
			}
			sb.append("\r\n<=========================>\n\r");
			sb.append("方法列表：");
			List<MethodNode> metheds = node.methods;
			for(MethodNode mn:metheds){
				sb.append("\r\n\t方法名：").append(mn.name).append("\t方法描述:").append(mn.desc).append("\r\n\t参数列表");
				List<Attribute> attrs = mn.attrs;
				if(attrs==null || attrs.size()==0){
					sb.append("\r\n\t\t----没有参数");
				}else{
				int i=1;
					for(Attribute at:attrs){
						sb.append("\r\n\t----参数").append(i++).append(" 类型:").append(at.isUnknown()?"未知类型":at.type);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
